package org.yang.plugins.cloud.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

/**
 * @Author lslands
 * @Version 1.0
 * @Date 2022/6/16 19:40
 * @PackageName:com.common.feign.handler
 * @ClassName: Oauth2ClientErrorHandler
 * @Description:    自定义 RestTemplate 异常处理
 */
@Configuration
public class RestTemplateErrorHandler implements ResponseErrorHandler {
    /**
     * 表示 response 是否存在任何错误。实现类通常会检查 response 的 HttpStatus。
     *
     * @param response
     * @return
     * @throws IOException
     */
    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        int rawStatusCode = response.getRawStatusCode();
        HttpStatus statusCode = HttpStatus.resolve(rawStatusCode);
        return (statusCode != null ? statusCode.isError() : hasError(rawStatusCode));
    }

    protected boolean hasError(int unknownStatusCode) {
        HttpStatus.Series series = HttpStatus.Series.resolve(unknownStatusCode);
        return (series == HttpStatus.Series.CLIENT_ERROR || series == HttpStatus.Series.SERVER_ERROR);
    }

    /**
     * 处理 response 中的错误, 当 hasError 返回 true 时才调用此方法。
     * 当返回异常信息时自己想要做的一些操作处理
     *
     * @param response
     * @throws IOException
     */
    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
    }

    /**
     * 覆盖了上面的方法
     * 处理 response 中的错误, 当 hasError 返回 true 时才调用此方法。
     * 当返回异常信息时自己想要做的一些操作处理
     *
     * @param url
     * @param method
     * @param response
     * @throws IOException
     */
    @Override
    public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
        InputStream inputStream = response.getBody();
        byte[] getData = readInputStream(inputStream);
        inputStream.read(getData);
        String str = new String(getData);
//        ExceptionResultDto result = JSON.parseObject(str, ExceptionResultDto.class);
//        throw new ServiceException(result.getMessage());
        JSONObject jsonObject = JSON.parseObject(str);
        String message = (String) jsonObject.get("message");
        System.out.println(message);
        //全局异常处理
    }

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

}
